package com.example.liyun.joy.news;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.Toast;

import com.example.liyun.joy.MainActivity;
import com.example.liyun.joy.MyItemDecoration;
import com.example.liyun.joy.MyRecycleAdapter;
import com.example.liyun.joy.R;
import com.example.liyun.joy.serviceutils.JokeBean;
import com.example.liyun.joy.serviceutils.LoaderResponce;
import com.example.liyun.joy.serviceutils.NewsBean;
import com.scwang.smartrefresh.header.BezierCircleHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.BallPulseFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.functions.Consumer;

@SuppressLint("ValidFragment")
public class tabFragment extends Fragment {
    private String[] strs;
    private RecyclerView mRecycleView;
    private LinearLayoutManager mLinearLayout;
    private MyRecycleAdapter mAdapter;
    private SmartRefreshLayout mSmartRefreshLayout;
    public View rootView;
    public Activity mActivity;
    private String name;
    final List<JokeBean.ResultBean.DataBean> jokeDatas = new ArrayList<>();
    final List<NewsBean.ResultBean.DataBean> newsDatas=new ArrayList<>();
    final LoaderResponce mLoader=new LoaderResponce();
    Handler handler;


    @Override
    public void onAttach(Context context) {//fragment嵌套Fragment 时，子Fragment的onAttach方法不执行。所以context需要手动传入
        super.onAttach(context);
        Log.d("getActivity","tabFragment"+String.valueOf((getActivity()!=null)));
    }

    public tabFragment(){
        super();
    }

    @SuppressLint("ValidFragment")
    public tabFragment(Context context,String name){
        //初始化数据，这是设置recycleView数据的数组，需要注意的是数组不能设置成静态static数组，不然每次创建的时候这个数组都会被覆盖
        strs=new String[30];
        for (int i=0;i<30;i++){
            int index=i+1;
            strs[i]=name+index;
        }
        this.name=name;
        mActivity= (Activity) context;

    }

    /**
     * 初始化数据
     * @param name 获取数据所对应条目的名称
     */
    public void initDatas(String name){
        switch (name){
            case "头条":
                getData("top");
                //getData("joke");
                break;
            case "社会":
                getData("shehui");
                //getData("joke");
                break;
            case "国内":
                getData("guonei");
                //getData("joke");
                break;
            case "国际":
                getData("guoji");
                //getData("joke");
                break;
            case "娱乐":
                getData("yule");
                //getData("joke");
                break;
            case "体育":
                getData("tiyu");
                //getData("joke");
                break;
            case "军事":
                getData("junshi");
                //getData("joke");
                break;
            case "科技":
                getData("keji");
                //getData("joke");
                break;
            case "财经":
                getData("caijing");
                //getData("joke");
                break;
            case "时尚":
                getData("shishang");
                //getData("joke");
                break;
            case "段子":
                getData("joke");
                break;
        }
    }

    /**
     * 统一传参，返回请求数据,Handler监听数据是否加载完成，加载完成后再传如数据
     * @param type
     * @return
     */
    private void getData(final String type) {
        mAdapter=new MyRecycleAdapter(getActivity(),type);
        mRecycleView.setAdapter(mAdapter);//必须要把数据加载下来后，recycleView才能设置adapter，否则无法显示
        handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {//通知更新并设置recycleView的数据
                super.handleMessage(msg);
                Log.i("jokeDatas","jokeDatas:"+jokeDatas.size());
                switch (msg.what){
                    case 1:
                        mAdapter.setJoke(jokeDatas);
                        jokeDatas.clear();
                        break;
                    case 2:
                        mAdapter.setNews(newsDatas);
                        newsDatas.clear();
                        Log.i("newsDatas","newsDatas:"+newsDatas.size()+mAdapter.getItemCount());
                        break;
                }
                /*getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //因为数据是异步请求的，在初始化设置时，布局时空的，所以数据完成加载请求，，需要通知adapter更新数据
                        mAdapter.notifyDataSetChanged();
                        mRecycleView.setAdapter(mAdapter);//必须要把数据加载下来后，recycleView才能设置adapter，否则无法显示
                    }
                });*/
            }
        };
        if (type.equals("joke")){
            mLoader.getDatas(1,20).subscribe(new Consumer<List<JokeBean.ResultBean.DataBean>>() {
                @Override
                public void accept(List<JokeBean.ResultBean.DataBean> dataBeans) throws Exception {
                    jokeDatas.addAll(dataBeans);
                    handler.sendEmptyMessage(1);//请求完成后，需要利用handler通知更新界面，不然得到的数据是空的
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) throws Exception {
                    Log.d("error", "trowable" + throwable.toString());
                }
            });
        }else{
            mLoader.getDatas(type).subscribe(new Consumer<List<NewsBean.ResultBean.DataBean>>() {
                @Override
                public void accept(List<NewsBean.ResultBean.DataBean> dataBeans) throws Exception {
                    newsDatas.addAll(dataBeans);
                    handler.sendEmptyMessage(2);//请求完成，通知更新recycleView
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) throws Exception {
                    Log.d("error","trowable"+throwable.toString());
                }
            });

        }

    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView=inflater.inflate(R.layout.tab_fragment,container,false);

        //设置上拉刷新下拉加载
        initSmartRefreshLayout();
        //设置recycleView
        initRecycleView();
        return rootView;
    }



    /**
     * 下拉刷新上拉加载
     */
    private void initSmartRefreshLayout() {
        mSmartRefreshLayout=rootView.findViewById(R.id.refreshLayout);
        //设置 Header 为 Material风格
        mSmartRefreshLayout.setRefreshHeader(new BezierCircleHeader(getActivity()));
        //设置 Footer 为 球脉冲
        mSmartRefreshLayout.setRefreshFooter(new BallPulseFooter(getActivity()));
        //设置强调颜色
        //mSmartRefreshLayout.setPrimaryColors();
        //下拉刷新监听器
        mSmartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                if (!name.equals("joke")){
                    mLoader.getDatas(name).subscribe(new Consumer<List<NewsBean.ResultBean.DataBean>>() {
                        @Override
                        public void accept(List<NewsBean.ResultBean.DataBean> dataBeans) throws Exception {
                            newsDatas.remove(25);
                            newsDatas.addAll(dataBeans);
                            handler.sendEmptyMessage(2);//请求完成，通知更新recycleView
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {
                            Log.d("error","trowable"+throwable.toString());
                        }
                    });
                }
                mSmartRefreshLayout.finishRefresh(3000);
            }
        });

        //上拉加载更多数据监听器
        mSmartRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            int i=1;
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {

                mLoader.getDatas(++i,5).subscribe(new Consumer<List<JokeBean.ResultBean.DataBean>>() {
                    @Override
                    public void accept(List<JokeBean.ResultBean.DataBean> dataBeans) throws Exception {
                        jokeDatas.addAll(dataBeans);
                        handler.sendEmptyMessage(1);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Log.d("error", "trowable" + throwable.toString());
                    }
                });
                mSmartRefreshLayout.finishLoadmore(3000);
            }
        });
    }

    /**
     * recycleview数据显示
     */
    private void initRecycleView() {

        //初始化设置RecycleView
        mRecycleView=rootView.findViewById(R.id.rv_list);
        //设置固定大小
        mRecycleView.setHasFixedSize(true);
        //创建布局类型
        mLinearLayout=new LinearLayoutManager(getActivity());
        //设置布局方向,注意：布局方向跟绘制分割线的方向是相对立的
        mLinearLayout.setOrientation(DividerItemDecoration.VERTICAL);
        //给RecycleView设置布局管理器
        mRecycleView.setLayoutManager(mLinearLayout);

        //创建适配器Adapter，并设置数据显示
        initDatas(name);//设置初始化数据。
        //mAdapter=new MyRecycleAdapter(getActivity(),strs);
        //mRecycleView.setAdapter(mAdapter);
        //设置RecycleView内Item的分割线,添加分割线,万能自定义分割线
        mRecycleView.addItemDecoration(new MyItemDecoration(getActivity(),LinearLayoutManager.HORIZONTAL,
                3,getActivity().getResources().getColor(R.color.colorAccent)));
        //mRecycleView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));


    }
}
